package com.springsecurity.dao.impl.weibo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import redis.clients.jedis.Jedis;

import com.springsecurity.dao.weibo.WeiboUserDAOI;
import com.springsecurity.entity.weibo.User;
import com.springsecurity.util.Constant;
import com.springsecurity.util.PasswordUtil;
import com.springsecurity.util.StringUtils;
import com.springsecurity.util.Utils;

@Repository
public class WeiboUserDAOImpl implements WeiboUserDAOI {

	@Autowired
	private Jedis redis;
	
	
	@Override
	public long register(User user) {
		long id=-1;
		
		//当前eamil没有注册过
		if(!redis.hexists(Constant.USER_EMAIL_TO_ID, user.getEmail())){
			//为用户生成id
			id=redis.incr(Constant.USER_COUNT);
			//插入email->id对应关系
			redis.hset(Constant.USER_EMAIL_TO_ID, user.getEmail(), String.valueOf(id));
			
			Map<String,String> map=new HashMap<>();
			map.put(Constant.EMAIL,user.getEmail());
			map.put(Constant.PASSWORD,PasswordUtil.encode(user.getPassword()));;
			map.put(Constant.NICKNAME, user.getNickname());
			map.put(Constant.REGIST_TIME, String.valueOf(System.currentTimeMillis()));;
			
			//写入user:[id]:data
			String key=String.format(Constant.USER_ID_DATA, id);
			redis.hmset(key, map);
		}
		return id;
	}

	@Override
	public boolean login(String email, String password) {
		String id=redis.hget(Constant.USER_EMAIL_TO_ID, email);
		if(!StringUtils.isEmpty(id)){
			String key=String.format(Constant.USER_ID_DATA, id);
			Map<String,String> map=redis.hgetAll(key);
			return PasswordUtil.checkEqual(password, map.get(Constant.PASSWORD));
		}
		return false;
	}

	@Override
	public long getUserId(String email) {
		String id=redis.hget(Constant.USER_EMAIL_TO_ID, email);
		if(!StringUtils.isEmpty(id)){
			return Long.valueOf(id);
		}
		return -1;
	}

	@Override
	public User getUser(long id) {
		String key=String.format(Constant.USER_ID_DATA, id);
		Map<String,String> map=redis.hgetAll(key);
		return Utils.mapToSimpleObject(map, User.class);
	}

	@Override
	public List<Long> newUserList(int limit) {
		Long maxId=Long.valueOf(redis.get(Constant.USER_COUNT));
		Long minId=maxId-(limit-1);
		if(minId<1){
			minId=1l;
		}
		List<Long> ids=new ArrayList<>((int)(maxId-minId+1));
		for(Long i=maxId;i>=minId;i--){
			ids.add(i);
		}
		return ids;
	}

}
